class EventEmitter {
  private events: Map<string, Function[]>;

  constructor() {
    this.events = new Map();
  }

  // 订阅事件
  on(eventName: string, callback: Function) {
    if (!this.events.has(eventName)) {
      this.events.set(eventName, []);
    }
    this.events.get(eventName)!.push(callback);
  }

  // 只订阅一次事件
  once(eventName: string, callback: Function) {
    const wrappedCallback = (...args: any[]) => {
      callback.apply(null, args);
      this.off(eventName, wrappedCallback);
    };
    this.on(eventName, wrappedCallback);
  }

  // 取消订阅事件
  off(eventName: string, callback: Function) {
    if (!this.events.has(eventName)) return;
    const callbacks = this.events.get(eventName)!;
    this.events.set(
      eventName,
      callbacks.filter((cb) => cb !== callback)
    );
  }

  // 发布事件
  emit(eventName: string, ...args: any[]) {
    if (!this.events.has(eventName)) return;
    const callbacks = this.events.get(eventName)!;
    callbacks.forEach((callback) => callback.apply(null, args));
  }
}

// 使用示例
const eventEmitter = new EventEmitter();

function handleEvent(data: any) {
  console.log("Event received:", data);
}

export default EventEmitter

// eventEmitter.on("testEvent", handleEvent);
// eventEmitter.emit("testEvent", "Hello, world!"); // 输出：Event received: Hello, world!
// eventEmitter.emit("testEvent", "Hello, world!"); // 输出：Event received: Hello, world!
//
// eventEmitter.once("testEventOnce", handleEvent);
// eventEmitter.emit("testEventOnce", "Hello, world!"); // 输出：Event received: Hello, world!
// eventEmitter.emit("testEventOnce", "Hello again!"); // 不会有输出，因为已经取消了订阅
//
// eventEmitter.off("testEvent", handleEvent);
// eventEmitter.emit("testEvent", "Hello, world!"); // 不会有输出，因为已经取消了订阅
